package com.songlanyun.modules.marketing.seckill.controller.admin;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.songlanyun.common.annotation.SysLog;
import com.songlanyun.common.enums.MarketingConstant;
import com.songlanyun.common.enums.OrderConstant;
import com.songlanyun.common.enums.PrivateMessageConstant;
import com.songlanyun.common.enums.SysConstant;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.DateUtils;
import com.songlanyun.common.utils.custom.DateCustomUtils;
import com.songlanyun.common.validator.ValidatorUtils;
import com.songlanyun.modules.account.service.AccountService;
import com.songlanyun.modules.account.service.UserInfoService;
import com.songlanyun.modules.exception.MarketingException;
import com.songlanyun.modules.marketing.seckill.entity.SeckillActivity;
import com.songlanyun.modules.marketing.seckill.model.dto.SeckillActivityDTO;
import com.songlanyun.modules.marketing.seckill.service.SeckillActivityService;
import com.songlanyun.modules.message.model.ActivityMessage;
import com.songlanyun.modules.message.model.to.MessageTO;
import com.songlanyun.modules.message.model.to.PrivateMessageTO;
import com.songlanyun.modules.message.service.SendPrivateMessageMsgService;
import com.songlanyun.modules.rabbitmq.MqConstant;

import com.songlanyun.modules.rabbitmq.service.SendMsgService;
import com.songlanyun.modules.user.controller.AbstractController;
import org.apache.ibatis.annotations.Delete;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.R;

import javax.annotation.Resource;


/**
 * 秒杀活动表
 *
 * @author Mark
 * @email sunlightcs@gmail.com
 * @date 2020-11-23 17:30:11
 */
@RestController
@RequestMapping("admin/marketing/seckillactivity")
public class SeckillActivityAdminController extends AbstractController {
    @Autowired
    private SeckillActivityService seckillActivityService;

    @Resource
    private AccountService accountService;

    @Resource
    private SendMsgService sendMsgService;

    /**
     * 列表
     */
    @GetMapping("/list")
//    @RequiresPermissions("seckill:seckillActivity:list")
    public R list(@RequestParam Map<String, Object> params) {
        params.put("shop_id", getShopId(true));
        PageUtils page = seckillActivityService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @GetMapping("/info/{id}")
//    @RequiresPermissions("seckill:seckillActivity:info")
    public R info(@PathVariable("id") Long id) {
        SeckillActivity seckillActivity = seckillActivityService.getInfoById(id);

        return R.ok().put("data", seckillActivity);
    }

    @Resource
    private SendPrivateMessageMsgService sendPrivateMessageMsgService;

    /**
     * 新建秒杀
     */
    @SysLog("新建秒杀")
    @PostMapping("/save")
//    @RequiresPermissions("seckill:seckillActivity:save")
    public R save(@RequestBody SeckillActivityDTO dto) {
        ValidatorUtils.validateEntity(dto);
        verifyName(dto.getName());//校验名称
        dto.setShopId(getShopId(true));//商铺id
        SeckillActivity seckillActivity = seckillActivityService.saveSeckill(dto);

        //发送站内消息    给商家下的所有会员
        sendPrivateMessageMsgService.send(new MessageTO(PrivateMessageConstant.MessageType.ACTIVITY_MESSAGE,
                PrivateMessageConstant.ModelType.SECKILL, seckillActivity.getId()));

        return R.ok();
    }

    /**
     * 修改秒杀
     */
    @SysLog("修改秒杀")
    @PutMapping("/update")
//    @RequiresPermissions("seckill:seckillActivity:update")
    public R update(@RequestBody SeckillActivityDTO dto) {
        ValidatorUtils.validateEntity(dto);
        //校验活动状态
        verifyActiveState(dto.getId(), 0);

        SeckillActivity seckillActivity = seckillActivityService.getById(dto.getId(), true);
        if (!seckillActivity.getName().equals(dto.getName())) {
            verifyName(dto.getName());//校验名称
        }
        seckillActivityService.updateSeckill(dto);

        return R.ok();
    }

    /**
     * 删除
     */
    @SysLog("删除秒杀")
    @DeleteMapping("/delete/{id}")
//    @RequiresPermissions("seckill:seckillActivity:delete")
    public R delete(@PathVariable("id") Long id) {
        //校验活动状态
        verifyActiveState(id, 1);

        seckillActivityService.delById(id);
        return R.ok();
    }

    /**
     * 校验活动状态
     *
     * @param id
     */
    private void verifyActiveState(Long id, Integer operationType) {
        SeckillActivity activity = seckillActivityService.getById(id, true);
        //开始时间
        Date startDate = DateUtils.stringToDate(DateCustomUtils.dateToString(activity.getStartTime()) + " " + activity.getStartHour());
        //结束时间
        Date endDate = DateUtils.stringToDate(DateCustomUtils.dateToString(activity.getEndTime()) + " " + activity.getEndHour());
        long timeMillis = System.currentTimeMillis();
        if (operationType == 0) {//修改
            //活动开始了就不能被修改了
            if (timeMillis > startDate.getTime()) {
                throw new RRException(MarketingException.SECKILL_ACTIVITY_START);
            }
        } else {//删除
            if (timeMillis > startDate.getTime()
                    && timeMillis <= endDate.getTime()) {
                throw new RRException(MarketingException.SECKILL_ACTIVITY_START);
            }
        }


//        //秒杀活动正在进行中，不能修改
//        if (MarketingConstant.ActiveState.UNDERWAY.equals(seckillActivity.getActiveState())) {
//            throw new RRException(MarketingException.SECKILL_ACTIVITY_UNDERWAY);
//        }
//        //秒杀活动已结束，不能修改
//        if (MarketingConstant.ActiveState.FINISHED.equals(seckillActivity.getActiveState())) {
//            throw new RRException(MarketingException.SECKILL_ACTIVITY_FINISH);
//        }
    }


    /**
     * 检验当前店铺的秒杀活动名称是否重复
     *
     * @param
     * @param name
     */
    private void verifyName(String name) {
        int count = seckillActivityService.count(
                new LambdaQueryWrapper<SeckillActivity>()
                        .eq(SeckillActivity::getShopId, getShopId(true))
                        .eq(SeckillActivity::getName, name)
        );
        if (count > 0) {
            throw new RRException(MarketingException.SECKILL_ACTIVITY_NAME_REPETITION);
        }
    }

}
